package org.water.common.util;

import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;


public class StringUtil {

	public StringUtil() {
		// TODO Auto-generated constructor stub
	}

	public static String CHECK_DIGIT[] = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
	public static int gene[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
	public static final int pass1 = 10;
	public static final int pass2 = 1;
	private static final char character[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
			'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
			'$', '_' };

	public static String trim(String str) {
		return isNull(str) ? "" : str.trim();
	}

	public static boolean isNull(String str) {
		return str == null;
	}

	public static boolean isEmpty(String str) {
		return isNull(str) || "".equals(str);
	}

	public static String nullToString(String str) {
		return isNull(str) ? "" : str;
	}

	public static String formartDate(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}

	public static String randomMath() {
		char character[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
				'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C',
				'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
				'Y', 'Z' };
		StringBuffer randomStr = new StringBuffer();
		for (int n = 0; n < 6; n++)
			randomStr.append(character[Math.abs((new Random()).nextInt(character.length)) % 62]);

		return randomStr.toString();
	}

	public static boolean isEmail(String email) {
		if (email == null || email.equals("")) {
			return false;
		} else {
			Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
			Matcher isMail = pattern.matcher(email);
			return isMail.matches();
		}
	}

	public static boolean isNum(String num) {
		if (num == null || num.equals("")) {
			return false;
		} else {
			Pattern pattern = Pattern.compile("[0-9]*");
			Matcher isNum = pattern.matcher(num);
			return isNum.matches();
		}
	}

	public static boolean isMobile(String mo) {
		if (mo == null || mo.equals("")) {
			return false;
		} else {
			Pattern pattern = Pattern.compile("^1[358]\\d{9}$");
			Matcher isMobile = pattern.matcher(mo);
			return isMobile.matches();
		}
	}

	public static boolean isIdentityCard(String card) {
		if (card == null || card.equals(""))
			return false;
		if (card.length() != 15 && card.length() != 18)
			return false;
		Pattern pattern = Pattern.compile("^(\\d{15}|(\\d{17}[xX\\d]))$");
		Matcher isIdentityCard = pattern.matcher(card);
		if (!isIdentityCard.matches())
			return false;
		if (card.length() == 18) {
			int yearPrefix = Integer.parseInt(card.substring(6, 8));
			if (yearPrefix < 19 || yearPrefix > 21)
				return false;
			int month = Integer.parseInt(card.substring(10, 12));
			if (month > 12 || month == 0)
				return false;
			int day = Integer.parseInt(card.substring(12, 14));
			if (day > 31 || day == 0)
				return false;
			String checkDigit = getCheckDigitFor18(card);
			if (checkDigit.equals("-1"))
				return false;
			return checkDigit.equals(card.substring(17, 18).toUpperCase());
		}
		if (card.length() == 15) {
			int month = Integer.parseInt(card.substring(8, 10));
			if (month > 12 || month == 0)
				return false;
			int day = Integer.parseInt(card.substring(10, 12));
			return day <= 31 && day != 0;
		} else {
			return false;
		}
	}

	private static String getCheckDigitFor18(String card) {
		if (card == null || card.equals(""))
			return "-1";
		int sum = 0;
		for (int i = 0; i < 17; i++)
			sum += Integer.parseInt(card.substring(i, i + 1)) * gene[i];

		return CHECK_DIGIT[sum % 11];
	}

	public static String getRandmStr(int length) {
		char tempCs[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o',
				'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm' };
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++)
			sb.append(tempCs[Math.abs(random.nextInt()) % tempCs.length]);

		return sb.toString();
	}

	public static int toNum(String str) {
		return Integer.parseInt(str);
	}

	public static int[] toNum(String str[]) {
		int i[] = new int[str.length];
		for (int j = 0; j < str.length; j++)
			i[j] = Integer.parseInt(str[j]);

		return i;
	}

	public static String repace(String str, String tag, String reStr) {
		if (isEmpty(str))
			return "";
		else
			return str.replaceAll(tag, reStr);
	}

	public static long toLong(String str) {
		return Long.parseLong(str);
	}

	public static Date toDate(String str) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return dateFormat.parse(str);
		} catch (ParseException e) {
			return null;
		}
	}
	public static Date toDate(String str,String format) {
		if(StringUtil.isEmpty(str))
		{
			return null;
		}
		else
		{
			DateFormat dateFormat = new SimpleDateFormat(format);
			try {
				return dateFormat.parse(str);
			} catch (ParseException e) {
				return null;
			}
		}
	}

	public static boolean isDateType(String args[]) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		df.setLenient(false);
		boolean isTag = true;
		try {
			for (int i = 0; i < args.length; i++)
				df.format(df.parse(args[i]));

		} catch (Exception e) {
			isTag = false;
		}
		return isTag;
	}

	public static boolean isFloat(boolean type, String args[]) {
		boolean isTag = true;
		try {
			if (type) {
				for (int i = 0; i < args.length; i++)
					Double.parseDouble(args[i]);

			} else {
				for (int i = 0; i < args.length; i++)
					if (!isNull(args[i]))
						Double.parseDouble(args[i]);

			}
		} catch (Exception e) {
			isTag = false;
		}
		return isTag;
	}

	public static double toDouble(String arg) {
		double dou = Double.parseDouble(arg);
		return dou;
	}

	public static float toFloat(String arg) {
		float flo = Float.parseFloat(arg);
		return flo;
	}

	public static boolean isEmptyObj(Object obj) {
		if (obj == null)
			return true;
		return isEmpty(obj.toString());
	}

	public static String objToString(Object obj) {
		if (!isEmptyObj(obj))
			return obj.toString();
		else
			return "";
	}

	public static String getPrimarykeyId() {
		return UUID.randomUUID().toString();
	}

	public static boolean validateSign(Map argsMap, String sign, String privateStringKey) {
		StringBuffer params = new StringBuffer();
		java.util.Map.Entry entry;
		for (Iterator iterator = argsMap.entrySet().iterator(); iterator.hasNext(); params.append(entry.getValue()))
			entry = (java.util.Map.Entry) iterator.next();

		return false;
	}

	public static String SHA256(String str) {
		String resultStr = "";
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-256");
			md.update(str.getBytes("GBK"));
			resultStr = (new HexBinaryAdapter()).marshal(md.digest());
			resultStr = resultStr.substring(0, 16);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultStr;
	}

	public static String formartDate(Date date, String formart) {
		SimpleDateFormat format = new SimpleDateFormat(formart);
		return format.format(date);
	}

	public static String DoEncrypt(String str) {
		StringBuffer enStrBuff = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			int tmpch = str.charAt(i);
			tmpch ^= 1;
			tmpch ^= 10;
			enStrBuff.append(Integer.toHexString(tmpch));
		}

		return enStrBuff.toString().toUpperCase();
	}

	public static String DoDecrypt(String str) {
		String deStr = str.toLowerCase();
		StringBuffer deStrBuff = new StringBuffer();
		for (int i = 0; i < deStr.length(); i += 2) {
			String subStr = deStr.substring(i, i + 2);
			int tmpch = Integer.parseInt(subStr, 16);
			tmpch ^= 1;
			tmpch ^= 10;
			deStrBuff.append((char) tmpch);
		}

		return deStrBuff.toString();
	}

	public static String getRandom() {
		Random random = new Random();
		int length = character.length;
		int n = random.nextInt(length);
		int b = random.nextInt(length);
		int c = random.nextInt(length);
		StringBuilder sb = new StringBuilder(3);
		sb.append(character[n]);
		sb.append(character[b]);
		sb.append(character[c]);
		return sb.toString();
	}

	public static String getRandom_() {
		char character[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
				'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
		Random random = new Random();
		int n = random.nextInt(character.length);
		int b = random.nextInt(character.length);
		StringBuilder sb = new StringBuilder(2);
		sb.append(character[n]);
		sb.append(character[b]);
		return sb.toString();
	}

	public static String getRandomAsTable() {
		char character[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
				'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
		Random random = new Random();
		int n = random.nextInt(character.length);
		int b = random.nextInt(character.length);
		StringBuilder sb = new StringBuilder(2);
		sb.append(character[n]);
		sb.append(character[b]);
		return sb.toString();
	}

	public static String replaceByIndex(String oldStr, String newStr, int index) {
		return (new StringBuilder(String.valueOf(oldStr.substring(0, index - 1)))).append(newStr)
				.append(oldStr.substring(index)).toString();
	}

	public static boolean isProtocol(String url) {
		return "http://".equals(url.substring(0, 7)) || "https://".equals(url.substring(0, 8));
	}
    /**
     * true转为true,否则为false
     * @param str
     * @return
     */
	public static boolean toBoolean(String str)
	{
		boolean r=false;
		if("true".equalsIgnoreCase(str))
		{
			r=true;
		}
		return r;
	}
}
